package org.example.top41_80;

import org.example.top40.TreeNode;

import java.util.HashMap;
import java.util.Scanner;

public class main78 {
    //从中序和后序遍历中构造二叉树
    //输入：inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]
    //输出：[3,9,20,null,null,15,7]
    static HashMap<Integer,Integer> map=new HashMap<>();
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] inorder = new int[n];
        int[] postorder = new int[n];
        for (int i = 0; i < n; i++) {
            inorder[i] = sc.nextInt();
        }
        for (int i = 0; i < n; i++) {
            postorder[i] = sc.nextInt();
        }

       TreeNode node=buildeTreeNode(inorder,postorder);
        System.out.println(node.left.val+","+node.right.val);
    }

    private static TreeNode buildeTreeNode(int[] inorder, int[] postorder) {
        int inLen = inorder.length;
        int postLen=postorder.length;
        for (int i = 0; i < inLen ; i++) {
            map.put(inorder[i],i);
        }
        TreeNode node=findNode(inorder,0,inLen,postorder,0,postLen);
        return node;
    }

    private static TreeNode findNode(int[] inorder, int inStart, int inEnd, int[] postorder, int postStart, int postEnd) {
        if(inStart>=inEnd||postStart>=postEnd){
            return null;
        }
        int rootIndex=map.get(postorder[postEnd-1]);
        TreeNode root = new TreeNode(inorder[rootIndex]);
        int leftofLen=rootIndex-inStart;
        root.left=findNode(inorder,inStart,rootIndex,postorder,postStart,postStart+leftofLen);
        root.right=findNode(inorder,rootIndex+1,inEnd,postorder,postStart+leftofLen,postEnd-1);
        return root;
    }
}
